package com.datastructure.test.partitionarray;

import java.util.Arrays;

public class PartitionArray {

    public static void main(String[] args) {
        PartitionArray partitionArray = new PartitionArray();
        int[] nums = {1,2,3,5};
        System.out.println(partitionArray.partition(nums));
    }

    public boolean partition (int[] nums) {
        // write code here
        int length = nums.length;
        Arrays.sort(nums);
        int sum = 0;
        int tempSum = 0;
        for (int num : nums) {
            sum+=num;
        }
        for (int i = length - 1; i >= 0; i--) {
            tempSum+=nums[i];
            sum-=nums[i];
            if(tempSum==sum){
                return true;
            }
        }
        return false;
    }

    public boolean partition1 (int[] nums) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }

        if ((sum & 1) != 0) {
            return false;
        }

        Arrays.sort(nums);

        return back(0, sum >> 1, 0, nums);
    }

    private boolean back(int res, int target, int index, int[] nums) {
        if (res == target) {
            return true;
        }

        if (index >= nums.length) {
            return false;
        }

        if (res + nums[index] > target) {
            return false;
        }

        for (int i = index; i < nums.length; i++) {
            if (back(res + nums[i], target, i + 1, nums)) {
                return true;
            }
            if (back(res, target, i + 1, nums)) {
                return true;
            }
        }

        return false;
    }
}
